<template>
  <div class="goods">
    <el-form class="third-form" inline ref="form" label-width="100px" @submit.prevent @keypress.enter="onSearchClick">
      <el-form-item label="商品名称">
        <el-input class="third_input" v-model="goodData.search.goodsName" placeholder="请输入商品名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-cascader v-model="goodData.search.goodsGrounp" :options="cateOptions" placeholder="请选择商品分类" clearable></el-cascader>
      </el-form-item>

      <el-form-item class="button-item">
        <div>
          <Button label="重置" @click="onResetClick" />
          <Button label="搜索" type="primary" @click="onSearchClick" />
        </div>
      </el-form-item>
    </el-form>

    <div class="outerTable">
      <div>
        <Button type="primary" label="新增商品" @click="onAddClick"></Button>
        <Button type="primary" label="批量上架" @click="onUpClick" :disabled="goodData.selected.length === 0" />
        <Button type="primary" label="批量下架" plain @click="onDownClick" :disabled="goodData.selected.length === 0" />
        <Button type="primary" label="批量删除" plain @click="onDeleleClick" :disabled="goodData.selected.length === 0" />
        <!-- <el-dropdown style="margin-left: 10px">
          <el-button type="primary" plain> 批量导出 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="onSelEcport">导出选中商品</el-dropdown-item>
              <el-dropdown-item @click="onAllExport">导出全部商品</el-dropdown-item>
              <el-dropdown-item @click="onSearchExport">导出搜索商品</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown> -->
      </div>

      <el-table ref="tableRef" :height="tableHeight" :data="goodData.list" @selection-change="onSelectionChange" v-loading="loading" @filter-change="onFilterChange">
        <el-table-column fixed="left" type="selection" width="50" />
        <el-table-column label="商品主图" prop="goodsImg">
          <template #default="scope">
            <img style="width: 72px; height: 72px" :src="scope.row.goodsImg.split(',')[0]" />
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column label="价格">
          <template #default="scope">
            <span style="display: inline-block; width: 70px">{{ scope.row.goodsSalesPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存">
          <template #default="scope">
            {{ scope.row.stock }}
          </template>
        </el-table-column>
        <el-table-column label="商品属性" prop="expandparamValue" />
        <el-table-column
          prop="auditStatus"
          label="审核状态"
          :formatter="(row, column, cellValue, index) => $formater.formaterAuditStatus(cellValue)"
          column-key="auditStatus"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.AuditStatus).map((key) => {
              return { text: consts.AuditStatus[key], value: key }
            })
          "
        >
          <template #default="scope">
            <el-tooltip v-if="scope.row.auditStatus === 'REJECTED'" popper-class="tooltip" effect="light" placement="bottom">
              <div>
                <span class="rejected">已驳回</span>
              </div>
              <template #content>
                <div>
                  <span>驳回原因: {{ `${scope.row.refuseReason}` }}</span>
                </div>
              </template>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="商品分类" width="120">
          <template #default="scope">
            {{ scope.row.goodsCatNameFirst + '/' + scope.row.goodsCatNameSecond + '/' + scope.row.goodsCatNameThird }}
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsStatus"
          label="上下架状态"
          :formatter="(row, column, cellValue, index) => $formater.formaterGoodsStatus(cellValue)"
          column-key="goodsStatus"
          :filter-multiple="false"
          :filters="
            Object.keys(consts.GoodsStatus).map((key) => {
              return { text: consts.GoodsStatus[key], value: key }
            })
          "
          width="120"
        />

        <el-table-column prop="putTime" label="上下架时间" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column fixed="right" label="操作" width="130">
          <template #default="scope">
            <Link label="编辑" @click="onEditClick(scope.row)" />
            <Link label="删除" @click="onDelClick(scope.row)" />
            <Link label="复制商品" @click="onCopyClick(scope.row)" :underline="false" />
          </template>
        </el-table-column>
      </el-table>
      <Pager :page="goodData.search.page" :pageSizes="goodData.search.pageSizes" :total="goodData.total" :limit="goodData.search.limit" @current-change="onCurrentChange" @size-change="onSizeChange" />
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import formater from '@/formater'
import consts from '@/consts'
import { calcTableHeight } from '@/assets/js/utils.js'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Pager from '@/components/pager/index.vue'

const router = useRouter()
const { tableRef, tableHeight } = calcTableHeight()

const goodData = reactive({
  total: 0,
  supplierList: [],
  list: [],
  search: {
    page: 1,
    limit: consts.Limit,
    pageSizes: consts.PageSize,
    goodsName: '',
    goodsStatus: '',
    goodsGrounp: []
  },
  gridData: {
    goodsSpecList: []
  },
  stock: '',
  selected: []
})

const cateOptions = ref([])

let goodsSpecVisible = ref(null)
let loading = ref(false)
let auditStatus = ref(false)

const delGood = async (row) => {
  let { err } = await api.post(`/medinstrument/third/goods/delById?goodsId=${row.goodsId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const delGoods = async (goodsIds) => {
  let { err } = await api.post(`/medinstrument/third/goods/batchDelByIds?goodsIds=${goodsIds}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const upOrDown = async (goodsIds, status) => {
  let { err } = await api.post(`/medinstrument/third/goods/batchUpdateGoodsStatus?goodsIds=${goodsIds}&goodsStatus=${status}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const getAllGoodsCategory = async () => {
  let { data, err } = await api.get('/medinstrument/third/goodsCategory/getAllGoodsCategory')
  if (err) {
    ElMessage.error(err)
  } else {
    cateOptions.value = data.result?.map((c1) => {
      return {
        label: c1.catName,
        value: c1.catId,
        children: c1.categoryChilden?.map((c2) => {
          return {
            label: c2.catName,
            value: c2.catId,
            children: c2.categoryChilden?.map((c3) => ({ label: c3.catName, value: c3.catId }))
          }
        })
      }
    })
  }
}

const loadData = async () => {
  loading.value = true

  let params = Object.assign({}, goodData.search)

  if (goodData.search.goodsGrounp) {
    params.goodsCatIdThird = goodData.search.goodsGrounp[goodData.search.goodsGrounp.length - 1]
    delete params.goodsGrounp
  }

  let { data, err } = await api.get('/medinstrument/third/goods/list', params)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    goodData.list = data.list
    goodData.total = data.count
  }
}

const onAddClick = () => {
  let { href } = router.resolve({
    path: `/goods/add`
  })
  window.open(href, '_blank')
}

const onEditClick = (row) => {
  let { href } = router.resolve({
    path: `/goods/edit/${row.goodsId}`
  })
  window.open(href, '_blank')
}

const onCopyClick = (row) => {
  let { href } = router.resolve({
    path: `/goods/edit/${row.goodsId}`,
    query: {
      t: 'c'
    }
  })
  window.open(href, '_blank')
}

const onDelClick = (row) => {
  ElMessageBox.confirm(`确定要删除商品${row.goodsName}吗，不可恢复？`, '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delGood(row)
    })
    .catch(() => {})
}

const onUpClick = () => {
  let noGoods = goodData.selected.filter((e) => e.auditStatus !== 'PASS')
  if (noGoods.length > 0) {
    ElMessage.error(`${noGoods?.map((e) => e.goodsName).join(' ')} 未审核不能上架`)
    return
  }
  let goodsIds = goodData.selected?.map((e) => e.goodsId).join(',')
  upOrDown(goodsIds, 'PUTON')
}

const onDownClick = () => {
  let goodsIds = goodData.selected?.map((e) => e.goodsId).join(',')
  upOrDown(goodsIds, 'PUTOFF')
}

const onDeleleClick = () => {
  ElMessageBox.confirm('确定要批量删除商品吗，不可恢复？', '系统', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let goodsIds = goodData.selected?.map((e) => e.goodsId).join(',')
      delGoods(goodsIds)
    })
    .catch(() => {})
}

const onResetClick = () => {
  goodData.search.goodsName = ''
  loadData()
}

const onSearchClick = () => {
  goodData.search.page = 1
  loadData()
}

const onCurrentChange = (val) => {
  goodData.search.page = val
  loadData()
}

const onSizeChange = (val) => {
  goodData.search.limit = val
  loadData()
}

const onSelectionChange = (val) => {
  goodData.selected = val
}

const onFilterChange = (filters) => {
  Object.keys(filters).forEach((e) => {
    goodData.search[e] = filters[e]
  })
  loadData()
}

onMounted(() => {
  loadData()
  getAllGoodsCategory()
})
</script>
<style scoped>
.rejected {
  position: relative;
  padding-bottom: 3px;
}
.rejected::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: var(--color-text);
}
</style>
<style>
.tooltip {
  width: 200px;
  max-height: 50px;
  padding: 15px 12px !important;
  line-height: 18px;
  box-shadow: 1px 1px 10px 3px #d3d3d6;
  font-size: 14px !important;
  color: var(--color-text) !important;
}
</style>
